package com.example.emp20221871luhaotian.demos.controller;

import com.example.emp20221871luhaotian.demos.po.Emp;
import com.example.emp20221871luhaotian.demos.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @author lht
 * @version 1.0
 * @since 2025/6/3
 */
@Controller
public class EmpController {

    @Autowired
    private EmpService empService;

    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("emps", empService.findAllEmp());
        return "list";
    }


    @GetMapping("/allSalary")
    public String summary(Model model) {
        model.addAttribute("salary", empService.getAllSalary());
        return "allSalary";
    }


    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("emp", new Emp());
        return "add";
    }


    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Integer id, Model model) {
        model.addAttribute("emp", empService.getById(id));
        return "edit";
    }


    // 添加/更新操作
    @PostMapping("/update")
    public String save(Emp emp) {
        if(emp.getId() == null) {
            empService.addEmp(emp);
        } else {
            empService.updateEmp(emp);
        }
        return "redirect:/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        empService.deleteEmp(id);
        return "redirect:/list";
    }
}
